﻿
(function () {

    var trackHost = "channel.hujiang.com";
    if (location.hostname.indexOf("dev.") != -1) {
        trackHost = "dev." + trackHost;
    }

    var domainName="hujiang.com";
    if (location.hostname.indexOf("hjclass.com") != -1){
        domainName="hjclass.com";
    } else if (location.hostname.indexOf("cctalk.com") != -1){
        domainName="cctalk.com";
    }

    function cookieExist(name) {
        return readCookie(name) != null;
    }

    function readCookie(c) {
        for (var c = c + "=", d = document.cookie.split(";"), b = 0; d.length > b; b++) {
            for (var a = d[b]; " " == a.charAt(0); ) {
                a = a.substring(1, a.length);
            }
            if (0 == a.indexOf(c)) {
                return decodeURIComponent(a.substring(c.length, a.length))
            }
        }
        return null;
    }

    function writeCookie(name, value, expireDays) {
        var now = new Date();
        var exdate = new Date(now.valueOf() + expireDays * 86400000);
        document.cookie = name + "=" + encodeURIComponent(value) + ((expireDays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/;domain="+domainName;
    }

    function loadJS(src) {
        var sc = document.createElement("script");
        sc.type = "text/javascript";
        sc.async = true;
        sc.src = src;
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(sc, s);
    }

    function getParame(url, name) {
        var r = new RegExp("(\\?|&)" + name + "=([^&]+)");
        var result = r.exec(url);
        return result ? decodeURIComponent(result[2]) : "";
    }

    function getUrlParame(name) {
        return getParame(location.search, name);
    }

    function getUserSearchKeyword() {
        var url = document.referrer || "";
        if (url == "") {
            return "";
        }

        var r = new RegExp("(\\?|&)(q|w|wd|word|query)=([^&]+)");
        var r_baidu = new RegExp("(\\?|&)(wd|word|w)=([^&]+)");
        var r_google = new RegExp("(\\?|&)(q)=([^&]+)");
        var r_sogou = new RegExp("(\\?|&)(query)=([^&]+)");
        var r_soso = new RegExp("(\\?|&)(w)=([^&]+)");
        var r_360 = new RegExp("(\\?|&)(q)=([^&]+)");

        if (url.indexOf(".baidu.com") != -1) {
            r = r_baidu;
        } else if (url.indexOf(".google.") != -1) {
            r = r_google;
        } else if (url.indexOf(".sogou.com") != -1) {
            r = r_sogou;
        } else if (url.indexOf(".soso.com") != -1) {
            r = r_soso;
        } else if (url.indexOf(".so.com") != -1 || url.indexOf(".360.cn") != -1) {
            r = r_360;
        } 

        var result = r.exec(url);

        if (result == null) {
            return "";
        }

        return decodeURIComponent(result[3]);
    }

    function getTodayString() {
        var d = new Date();

        var year = d.getFullYear();
        var month = (d.getMonth() + 1).toString();
        var day = d.getDate().toString();

        return year + "-" + month + "-" + day;
    }

    function getFullDateString() {
        var d = new Date();

        var year = d.getFullYear().toString();
        var month = (d.getMonth() + 1).toString();
        var day = d.getDate().toString();

        if (month.length == 1) {
            month = "0" + month;
        }

        if (day.length == 1) {
            day = "0" + day;
        }

        return year + month + day;
    }

    function randNum(n) {
        var rnd = "";
        for (var i = 0; i < n; i++)
            rnd += Math.floor(Math.random() * 10);
        return rnd;
    }

    function createUID() {
        return ((new Date().getTime() - new Date(2013, 0, 1)).toString()) + randNum(3).toString()
    }

    function sendByImage(src) {
        var img = new Image(1, 1);
        img.onload = img.onerror = img.onabort = function () {
            img.onload = img.onerror = img.onabort = null;
        }
        img.src = src;
    }

    function trackUA() {
        window.ga = window.ga || function () { (ga.q = ga.q || []).push(arguments) };

        var ga_userid = window.ga_userid || 0;
        var ga_username = window.ga_username || "";

        ga("create", "UA-39958636-1", {
            "name": "ca",
            "cookieName": "_ga_channel",
            "cookieDomain": domainName
        });

        if (ga_userid != 0) {
            var ga_userinfo = ga_userid + "_" + ga_username;
            ga("ca.set", "dimension11", ga_userinfo);
        }

        if (cookieExist("channel_landing_page")) {
            ga("ca.set", "dimension12", readCookie("channel_landing_page"));
        }

        if (cookieExist("channel_refer")) {
            ga("ca.set", "dimension13", readCookie("channel_refer"));
        }

        // mark create_date
        if (readCookie("channel_source") == null) {
            ga("ca.set", "dimension1", getFullDateString());
        }

        // kf url rewrite
        if (location.hostname == "class.hujiang.com") {
            var m = location.href.match(/\/(\d+)\/intro/i);
            if (m != null) {
                var classID = m[1];
                $("#class_kf a").click(function () {
                    ga("ca.send", "pageview", "/" + classID + "/hj_kf/");
                });
            }
        }

        if (location.search.indexOf("sem_source=") != -1 ) {
            
            if ((getUrlParame("sem_source") == "sem_baidu" || 
                 getUrlParame("sem_source") == "sem_baidu_class") && location.search.indexOf("keywordid=") != -1) {
                
                window.ga_sem_callback = function (item) {
                    if (item != null) {
                        var keywordID = item.keywordID;
                        var matchKeyword = item.keyword;
                        var matchType = item.matchType;
                        var price = item.price;

                        var userSearch = getUserSearchKeyword();

                        var url = location.pathname + location.search;

                        url = url + "&utm_term=" + matchKeyword;
                   
                        ga("ca.set", "dimension5", getUrlParame("utm_source"));
                        ga("ca.set", "dimension6", getUrlParame("utm_medium"));

                        ga("ca.set", "dimension7", getUrlParame("utm_campaign"));
                        ga("ca.set", "dimension8", getUrlParame("utm_adgroup"));
                        ga("ca.set", "dimension9", getUrlParame("utm_content"));
                        ga("ca.set", "dimension10", matchKeyword);

                        // utm_match_type
                        ga("ca.set", "dimension2", matchType);

                        // utm_keyword_id
                        ga("ca.set", "dimension4", keywordID.toString());

                        // utm_keyword_user
                        ga("ca.set", "dimension3", userSearch);

                        ga("ca.set", "metric1", price.toString());

                        ga("ca.send", "pageview", url);
                    } else {
                        // todo: set default dimension info
                        ga("ca.send", "pageview");
                    }
                };

                var keywordID = getUrlParame("keywordid");
                var sem_source = getUrlParame("sem_source");
                loadJS("http://" + trackHost + "/sem_query.ashx?keywordid=" + keywordID + "&sem_source=" + sem_source);

            } else {
                
                var userSearch = getUserSearchKeyword();

                ga("ca.set", "dimension5", getUrlParame("utm_source"));
                ga("ca.set", "dimension6", getUrlParame("utm_medium"));

                ga("ca.set", "dimension7", getUrlParame("utm_campaign"));
                ga("ca.set", "dimension8", getUrlParame("utm_adgroup"));
                ga("ca.set", "dimension9", getUrlParame("utm_content"));
                ga("ca.set", "dimension10", getUrlParame("utm_term"));

                // for adwords
                var matchType = getUrlParame("utm_matchtype")
                if (matchType != "") {
                    if (matchType == "e") {
                        matchType = "exact";
                    } else if (matchType == "p") {
                        matchType = "phrase"
                    } else if (matchType == "b") {
                        matchType = "broad";
                    }

                    // utm_match_type
                    ga("ca.set", "dimension2", matchType);
                }

                // utm_keyword_user
                ga("ca.set", "dimension3", userSearch);

                ga("ca.send", "pageview");
            }

        } else {
            ga("ca.send", "pageview");
        }

        (function (i, s, o, g, r, a, m) {
            i["GoogleAnalyticsObject"] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
			m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, "script", "//common.hjfile.cn/analytics/google/analytics.js", "ga");
    }

    function track() {
        var version = 13;
        var expireDays = 30;

        var url = encodeURIComponent(location.href);
        var refer = encodeURIComponent(document.referrer);
        var title = encodeURIComponent(document.title);
        var channelType = "";
        var uid = "";
        var channelSource = "";
        if (!cookieExist("channel_source")) {
            channelSource = getUrlParame("sem_source");
            if (channelSource != "") {
                channelType = "sem";
            } else {
                channelSource = getUrlParame("pp_source");
                channelType = "pp";
            }

            if (channelSource != "") {
                uid = createUID();
                writeCookie("channel_source_type", channelType, expireDays);
                writeCookie("channel_source", channelSource, expireDays);

                writeCookie("channel_uid", uid, expireDays);
                writeCookie("channel_version", version, expireDays);
                writeCookie("channel_landing_page", location.href, expireDays);
                writeCookie("channel_refer", document.referrer, expireDays);
                writeCookie("channel_time", (new Date()).getTime(), expireDays);
            }
        }else{
            channelType = readCookie("channel_source_type");
            uid = readCookie("channel_uid");
            channelSource = readCookie("channel_source");
        }

		var protocol = /^https?:$/.test(location.protocol) && location.protocol || 'https:';
		
        var src = protocol + "//" + trackHost + "/channel_click.ashx" + "?url=" + url +
                  "&refer=" + refer + "&title=" + title + "&version=" + version + 
                  "&r=" + (new Date()).getTime() + "&ct=" + channelType + "&cs=" + channelSource + 
                  "&cu=" + uid + "&clp=" + url + "&cr=" + refer;

        sendByImage(src);
    }

    track();
    //trackUA();
})();